//
//  PayMoneyLatestDetailViewController.m
//  PropertyManager
//
//  Created by TNG on 2018/8/28.
//  Copyright © 2018年 Tng. All rights reserved.
//

#import "PayMoneyLatestDetailViewController.h"

@interface PayMoneyLatestDetailViewController () <UITableViewDelegate,UITableViewDataSource,WXApiDelegate>

@property (strong, nonatomic) UITableView * tableview;
@property (strong, nonatomic) UIButton * btn;
@property (strong, nonatomic) PayMoneyModel * detailInfoModel;
@property (strong, nonatomic) HistoryPayModel * detailHistoryModel;
@property (strong, nonatomic) overDueNoPayModel * detailOverDueModel;

@end

@implementation PayMoneyLatestDetailViewController

static NSString * cellID = @"cell";
static NSString * PayLatestMoneyTableViewCellID = @"PayLatestMoneyTableViewCell";
static NSString * PayLatestNullTableViewCellID = @"PayLatestNullTableViewCell";
static NSString * PayLatestDetailTableViewCellID = @"PayLatestDetailTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"缴费账单详情";
    [self creatTableview];
    [self registCell];
    if (self.isPay) {
        [self.view addSubview:self.btn];
    }
    [self wr_setNavBarShadowImageHidden:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AliPayDidBack:) name:@"AliPayDidBack" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weiXinPayDidBack:) name:@"weiXinPayDidBack" object:nil];
    if (self.model != nil) {
        [self RequestData];
    }else if (self.overDueNoPayModel != nil)
    {
        [self overDueDetailData];
    }else
    {
        [self historyDetailData];
    }
}

#pragma mark - Data
-(void)RequestData
{
    WeakSelf;
    NSString * urlStr = [NSString stringWithFormat:@"/rest/gbBqsftzdController/get?pkCustomerid=%@&pkPact=%@&busreceivemonth=%@&pkHouse=%@&faretype=%@",SFMgbuserid,self.model.pkPact,self.model.busreceivemonth,self.model.pkHouse,self.model.faretype];
    [[HTTPClient shareClient] requestWithPath:urlStr AndReturnBlock:^(NSDictionary *dic) {
        NSDictionary * dics = dic[@"data"];
        PayMoneyModel * model = [PayMoneyModel modelWithDic:dics];
        weakSelf.detailInfoModel = model;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableview reloadData];
        });
    } AndFailMessage:^(NSString *message, NSString *errorCode) {
        [SVProgressHUD ShowErrorMessage:message];
    }];
}

-(void)historyDetailData{
    WeakSelf;
    NSString * urlStr = [NSString stringWithFormat:@"/rest/gbJfjljfpController/get?pkCustomerid=%@&pkPact=%@&busreceivemonth=%@&pkHouse=%@&faretype=%@",SFMgbuserid,self.historyPayModel.pkPact,self.historyPayModel.busreceivemonth,self.historyPayModel.pkHouse,self.historyPayModel.faretype];
    [[HTTPClient shareClient] requestWithPath:urlStr AndReturnBlock:^(NSDictionary *dic) {
        NSDictionary * dics = dic[@"data"];
        HistoryPayModel * model = [HistoryPayModel modelWithDic:dics];
        weakSelf.detailHistoryModel = model;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableview reloadData];
        });
    } AndFailMessage:^(NSString *message, NSString *errorCode) {
        [SVProgressHUD ShowErrorMessage:message];
    }];
}

-(void)overDueDetailData
{
    WeakSelf;
    NSString * urlStr = [NSString stringWithFormat:@"rest/gbYqwjqdController/get?pkCustomerid=%@&pkPact=%@&busreceivemonth=%@&pkHouse=%@&faretype=%@",SFMgbuserid,self.overDueNoPayModel.pkPact,self.overDueNoPayModel.busreceivemonth,self.overDueNoPayModel.pkHouse,self.overDueNoPayModel.faretype];
    [[HTTPClient shareClient] requestWithPath:urlStr AndReturnBlock:^(NSDictionary *dic) {
        NSDictionary * dics = dic[@"data"];
        overDueNoPayModel * model = [overDueNoPayModel modelWithDic:dics];
        weakSelf.detailOverDueModel = model;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableview reloadData];
        });
    } AndFailMessage:^(NSString *message, NSString *errorCode) {
        [SVProgressHUD ShowErrorMessage:message];
    }];
}

#pragma mark -微信回调
-(void)weiXinPayDidBack:(NSNotification *)notice
{
    NSDictionary * dic = notice.userInfo;
    NSString * code = dic[@"code"];
    WeakSelf;
    if ([code isEqualToString:@"0"]) {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"支付成功" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            ElectronTicketViewController * ctr =[[ElectronTicketViewController alloc] init];
            [weakSelf.navigationController pushViewController:ctr animated:YES];
        }];
        [alert addAction: action1];
        [self presentViewController:alert animated:YES completion:nil];
    }else
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"支付失败" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
        [alert addAction: action1];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

#pragma mark - 支付宝回调
-(void)AliPayDidBack:(NSNotification *)notice
{
    NSDictionary * dic = notice.userInfo;
    NSString * str =dic[@"resultStatus"];
    NSString * payMessage  = @"支付失败";
    if ([str isEqualToString:@"6001"]) {
        payMessage  = @"支付失败";
    }else if([str isEqualToString:@"6002"])
    {
        payMessage  = @"网络延迟,请稍后再试";
    }else if([str isEqualToString:@"9000"])
    {
        payMessage  = @"支付成功";
    }else
    {
        payMessage  = @"交易延迟,请稍后再试";
    }
    WeakSelf;
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:payMessage message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([payMessage isEqualToString:@"支付成功"]) {
            ElectronTicketViewController * ctr =[[ElectronTicketViewController alloc] init];
            [weakSelf.navigationController pushViewController:ctr animated:YES];
        }
    }];
    [alert addAction: action1];
    [weakSelf presentViewController:alert animated:YES completion:nil];
}
-(void)registCell
{
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    [self.tableview registerClass:[PayLatestMoneyTableViewCell class] forCellReuseIdentifier:PayLatestMoneyTableViewCellID];
    [self.tableview registerClass:[PayLatestNullTableViewCell class] forCellReuseIdentifier:PayLatestNullTableViewCellID];
    [self.tableview registerClass:[PayLatestDetailTableViewCell class] forCellReuseIdentifier:PayLatestDetailTableViewCellID];
}

-(void)creatTableview{
    if (self.tableview == nil) {
        UITableView * tableview;
        if (self.isPay) {
            tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kStatusAndNavBarH, WIDTH, HEIGHT - kStatusAndNavBarH - kHomeLineH - 50) style:UITableViewStyleGrouped];
        }else
        {
            tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kStatusAndNavBarH, WIDTH, HEIGHT - kStatusAndNavBarH - kHomeLineH) style:UITableViewStyleGrouped];
        }
        tableview.delegate = self;
        tableview.dataSource = self;
        tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        }
        self.tableview = tableview;
        [self.view addSubview:self.tableview];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        return 217;
    }else if (indexPath.row == 5)
    {
        return 93;
    }
    return 32;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        PayLatestMoneyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PayLatestMoneyTableViewCellID];
        if (self.detailInfoModel != nil) {
            [cell sendPayMoneyModel:self.detailInfoModel];
        }else if (self.detailHistoryModel != nil)
        {
            [cell sendHistoryPayModel:self.detailHistoryModel];
        }else
        {
            [cell sendoverDueNoPayModel:self.detailOverDueModel];
        }
        return cell;
    }else if (indexPath.row == 5)
    {
        PayLatestNullTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PayLatestNullTableViewCellID];
        return cell;
    }else
    {
        PayLatestDetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PayLatestDetailTableViewCellID];
        if (self.detailInfoModel != nil) {
            if (indexPath.row == 1) {
                cell.titleLabel.text = @"记账周期";
                cell.detailLabel.text = self.detailInfoModel.fareperiod;
            }else if (indexPath.row == 2)
            {
                cell.titleLabel.text = @"出账日";
                cell.detailLabel.text = self.detailInfoModel.busreceivemonth;
            }else if (indexPath.row == 3)
            {
                cell.titleLabel.text = @"合同编号";
                cell.detailLabel.text = self.detailInfoModel.pkPact;
            }else
            {
                cell.titleLabel.text = @"缴费状态";
                cell.detailLabel.text = @"待缴费";
            }
        }else if (self.detailHistoryModel != nil)
        {
            if (indexPath.row == 1) {
                cell.titleLabel.text = @"记账周期";
                cell.detailLabel.text = self.detailHistoryModel.fareperiod;
            }else if (indexPath.row == 2)
            {
                cell.titleLabel.text = @"出账日";
                cell.detailLabel.text = self.detailHistoryModel.busreceivemonth;
            }else if (indexPath.row == 3)
            {
                cell.titleLabel.text = @"合同编号";
                cell.detailLabel.text = self.detailHistoryModel.pkPact;
            }else
            {
                cell.titleLabel.text = @"缴费状态";
                cell.detailLabel.text = @"已缴费";
            }
        }else
        {
            if (indexPath.row == 1) {
                cell.titleLabel.text = @"记账周期";
                cell.detailLabel.text = self.detailOverDueModel.fareperiod;
            }else if (indexPath.row == 2)
            {
                cell.titleLabel.text = @"出账日";
                cell.detailLabel.text = self.detailOverDueModel.busreceivemonth;
            }else if (indexPath.row == 3)
            {
                cell.titleLabel.text = @"合同编号";
                cell.detailLabel.text = self.detailOverDueModel.pkPact;
            }else
            {
                cell.titleLabel.text = @"缴费状态";
                cell.detailLabel.text = @"已逾期";
            }
        }
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(BOOL)hidesBottomBarWhenPushed
{
    return YES;
}

-(UIButton *)btn
{
    if (_btn == nil) {
        _btn = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableview.frame), WIDTH, 50)];
        [_btn setTitle:@"确认缴费" forState:UIControlStateNormal];
        _btn.titleLabel.font = font(16);
        [_btn setBackgroundColor:SFMNavBarColor];
        [_btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn;
}

#pragma mark - 确认缴费
-(void)btnClick:(UIButton *)btn{
    ElectronTicketViewController * ctr =[[ElectronTicketViewController alloc] init];
    [self.navigationController pushViewController:ctr animated:YES];
    return;
    WeakSelf;
    [[PayMedthView shareView] showView];
    [PayMedthView shareView].payMedthChooseTypeEventBlock = ^(int payType) {
        if (payType == payMedthodWayOfAliPay) {
            [weakSelf AliPay:btn];
        }else if(payType == payMedthodWayofWeiChat) {
            [weakSelf weiXinPay];
        }
    };
}

#pragma mark - 支付宝支付
-(void)AliPay:(UIButton *)btn
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setValue:@"0.01" forKey:@"totalAmount"];
    WeakSelf;
    [[HTTPClient shareClient] requestWithPath:@"/rest/alipay/appPay" AndParams:params AndReturnBlock:^(NSDictionary *dic) {
        NSString *appScheme = @"GuangBaiCompanyApp";
        NSString * orderString = dic[@"data"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                NSString * str =resultDic[@"resultStatus"];
                NSString * payMessage  = @"支付失败";
                if ([str isEqualToString:@"6001"]) {
                    payMessage  = @"支付失败";
                }else if([str isEqualToString:@"6002"])
                {
                    payMessage  = @"网络延迟,请稍后再试";
                }else if([str isEqualToString:@"9000"])
                {
                    payMessage  = @"支付成功";
                }else
                {
                    payMessage  = @"交易延迟,请稍后再试";
                }
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:payMessage message:@"" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    if ([payMessage isEqualToString:@"支付成功"]) {
                        ElectronTicketViewController * ctr = [[ElectronTicketViewController alloc] init];
                        [weakSelf.navigationController pushViewController:ctr animated:YES];
                    }
                }];
                [alert addAction: action1];
                [weakSelf presentViewController:alert animated:YES completion:nil];
            }];
            weakSelf.btn.userInteractionEnabled = YES;
        });
    }AndFailMessage:^(NSString *message, NSString *errorCode) {
        [MBProgressHUD showMessageWithDelay:message delay:2];
        weakSelf.btn.userInteractionEnabled = YES;
    }];
}

#pragma mark - 微信支付
-(void)weiXinPay
{
    //    int money = [self.money floatValue]*100;
    //
    //    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    //    [params setValue:SFMsignKey forKey:@"signKey"];
    //    [params setValue:[NSString stringWithFormat:@"%d",money] forKey:@"txnAmt"];
    //
    //    WeakSelf;
    //    [[TNGHTTP shareHttpClient] requestWithPath:@"app/unionpay/wxApppay" AndParams:params AndReturnBlock:^(NSDictionary *dic) {
    //        NSDictionary * dict = dic[@"map"];
    //        NSString * partnerId = [NSString stringWithFormat:@"%@",dict[@"mch_id"]];
    //        NSString * prepayId  = [NSString stringWithFormat:@"%@",dict[@"prepay_id"]];
    //        NSString * nonceStr  = [NSString stringWithFormat:@"%@",dict[@"nonce_str"]];
    //        NSString * sign      = [NSString stringWithFormat:@"%@",dict[@"sign"]];
    //        NSString * timestamp = [NSString stringWithFormat:@"%@",dict[@"timestamp"]];
    //
    //        //调起微信支付
    //        PayReq * req            = [[PayReq alloc] init];
    //        req.partnerId           = partnerId;
    //        req.prepayId            = prepayId;
    //        req.nonceStr            = nonceStr;
    //        req.timeStamp           = [timestamp intValue];
    //        req.sign                = sign;
    //        req.package             = @"Sign=WXPay";
    //        [WXApi sendReq:req];
    //        weakSelf.sureBtn.userInteractionEnabled = YES;
    //    }AndFailMessage:^(NSString * message) {
    //        [MBProgressHUD showMessageWithDelay:message delay:2];
    //        weakSelf.sureBtn.userInteractionEnabled = YES;
    //    }];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AliPayDidBack" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"weiXinPayDidBack" object:nil];
}

-(void)onResp:(BaseResp *)resp
{
    if ([resp isKindOfClass:[PayResp class]])
    {
        WeakSelf;
        NSString * code = [NSString stringWithFormat:@"%d",resp.errCode];
        if ([code isEqualToString:@"0"]) {
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"支付成功" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                ElectronTicketViewController * ctr =[[ElectronTicketViewController alloc] init];
                [weakSelf.navigationController pushViewController:ctr animated:YES];
            }];
            [alert addAction: action1];
            [self presentViewController:alert animated:YES completion:nil];
        }else
        {
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"支付失败" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alert addAction: action1];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
